package it.pecuswap.commons.utils;

import it.pecuswap.commons.exceptions.PecuswapMailException;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class MailClientMock {
	
	private final static Logger logger = Logger.getLogger(MailClientMock.class);

	final static String username = "test";
	final static String password = "test";
	final static String to = "mokedto@test.it";
	final static String smtpServer = "localhost";
	
	static Properties mailServerProperties;
	static Session getMailSession;
	static MimeMessage generateMailMessage;

	public static void sendMailWithRegistrationToken(String tokenRegistrazione, long idUtente) throws PecuswapMailException{
		String linkRegistrazione = "http://localhost:8080/PecuSwapFrontend/registrazioneSecond?token=" +
				tokenRegistrazione + "&id=" + idUtente;
		String emailBody = "Prova mail registrazione \n\r link: " + linkRegistrazione;
		sendMail(emailBody);
	}
	
	public static void sendMail(String emailBody) throws PecuswapMailException {
		
		mailServerProperties = System.getProperties();
		mailServerProperties.put("mail.smtp.port", "25");
		mailServerProperties.put("mail.smtp.auth", "true");
		mailServerProperties.put("mail.smtp.starttls.enable", "true");
		
		Transport transport = null;
 
		getMailSession = Session.getDefaultInstance(mailServerProperties, null);
		generateMailMessage = new MimeMessage(getMailSession);
		try {
			generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
			generateMailMessage.setSubject("[PECUSWAP] - Registrazione");
			generateMailMessage.setContent(emailBody, "text/html");

			transport = getMailSession.getTransport("smtp");
		} catch (AddressException e) {
			logger.error("Errore durante l'impostazione del destinatario", e);
			throw new PecuswapMailException(e);
		} catch (MessagingException e) {
			logger.error("Errore durante l'impostazione della mail", e);
			throw new PecuswapMailException(e);
		}
 
		
		try {
			transport.connect(smtpServer, username, password);
			transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
			transport.close();
		} catch (MessagingException e) {
			logger.error("Errore durante l'INVIO della mail", e);
			throw new PecuswapMailException(e);
		}
	}
	
}
